import React, { useEffect, useRef, useState } from "react";
import {
  CloseOutlined,
  CloudUploadOutlined,
  CommentOutlined,
  DeleteOutlined,
  PlusOutlined,
  RedoOutlined,
} from "@ant-design/icons";
import {
  Attachments,
  type AttachmentsProps,
  Bubble,
  Conversations,
  Sender,
  Suggestion,
  Welcome,
} from "@ant-design/x";
import type { Conversation } from "@ant-design/x/es/conversations";
import {
  Button,
  GetProp,
  GetRef,
  Popover,
  Popconfirm,
  Space,
  Spin,
} from "antd";
import dayjs from "dayjs";
import type { Answer, CopilotProps, MessageItem } from "./types";
import { useCopilotStyle } from "./styles";
import { useChatAgent } from "./useChatAgent";
import { createChat, createMarkdownRenderer, generateId } from "./utils";
import { getMockSuggestions } from "./constants";
import { MessageContext } from "../../App";
import HumanInputModal from "./HumanInputModal";
import {
  HumanInputMessage,
} from "./stoppedOperations";
import { FlightOption, getProductById, saveProductMultilang, type SaveProductMultilangRequest } from "../../services/apiService";
import { useTranslation } from 'react-i18next';
import LanguageSwitcher from "../../components/LanguageSwitcher";

// ==================== LocalStorage Utils ====================
const STORAGE_KEYS = {
  MESSAGE_HISTORY: "copilot_message_history",
  SESSION_LIST: "copilot_session_list",
  CURRENT_SESSION: "copilot_current_session",
  CHAT_IDS: "copilot_chat_ids", // 新增：存储每个会话的 chatId
};

// 生成唯一的 chatId
const generateChatId = () => {
  return generateId("chat");
};

const saveToLocalStorage = (key: string, data: any) => {
  try {
    localStorage.setItem(key, JSON.stringify(data));
  } catch (error) {
    console.error("Failed to save to localStorage:", error);
  }
};

const loadFromLocalStorage = (key: string, defaultValue: any = null) => {
  try {
    const item = localStorage.getItem(key);
    return item ? JSON.parse(item) : defaultValue;
  } catch (error) {
    console.error("Failed to load from localStorage:", error);
    return defaultValue;
  }
};

const Copilot: React.FC<CopilotProps> = ({
  copilotOpen,
  setCopilotOpen,
  setDisplayHtml,
  setDisplayProductId,
  currentDisplayType: externalCurrentDisplayType,
  setCurrentDisplayType: externalSetCurrentDisplayType,
  setFlightState,
}) => {
  const { styles } = useCopilotStyle();
  const attachmentsRef = useRef<GetRef<typeof Attachments>>(null);
  const messageApi = React.useContext(MessageContext);
  const { t, i18n } = useTranslation();

  // 使用外部状态或内部状态
  const [internalCurrentDisplayType, setInternalCurrentDisplayType] = useState<
    "html" | "product" | null
  >(null);
  const currentDisplayType =
    externalCurrentDisplayType !== undefined
      ? externalCurrentDisplayType
      : internalCurrentDisplayType;
  const setCurrentDisplayType =
    externalSetCurrentDisplayType || setInternalCurrentDisplayType;

  // ==================== State ====================
  const defaultSessionList = [
    {
      key: "0",
      label: t('copilot.newSession'),
      group: t('copilot.history'),
    },
  ];

  const [messageHistory, setMessageHistory] = useState<Record<string, any>>(
    () => loadFromLocalStorage(STORAGE_KEYS.MESSAGE_HISTORY, {}),
  );
  const [sessionList, setSessionList] = useState<Conversation[]>(() =>
    loadFromLocalStorage(STORAGE_KEYS.SESSION_LIST, defaultSessionList),
  );
  const [chatIds, setChatIds] = useState<Record<string, string>>(() =>
    loadFromLocalStorage(STORAGE_KEYS.CHAT_IDS, {}),
  );
  const [curSession, setCurSession] = useState(() => {
    const savedSession = loadFromLocalStorage(
      STORAGE_KEYS.CURRENT_SESSION,
      null,
    );
    const savedSessionList = loadFromLocalStorage(
      STORAGE_KEYS.SESSION_LIST,
      defaultSessionList,
    );
    // 确保当前会话在会话列表中存在
    const sessionExists = savedSessionList.some(
      (session: any) => session.key === savedSession,
    );
    return sessionExists ? savedSession : savedSessionList[0]?.key || "0";
  });
  const [attachmentsOpen, setAttachmentsOpen] = useState(false);
  const [files, setFiles] = useState<GetProp<AttachmentsProps, "items">>([]);
  const [inputValue, setInputValue] = useState("");

  // 人工确认相关状态
  const [humanInputModal, setHumanInputModal] = useState({
    visible: false,
    nodeId: "",
    nodeLabel: "",
    nodeData: null as any,
    humanInputMessage: null as HumanInputMessage | null,
  });

  // 航班选择相关状态
  const [flightSelectionModal, setFlightSelectionModal] = useState({
    visible: false,
    nodeId: "",
    nodeLabel: "",
    nodeData: null as any,
  });

  // ==================== Hooks ====================
  // 包装 setDisplayHtml 和 setDisplayProductId 来跟踪显示类型
  const handleDisplayHtml = (content: string) => {
    setDisplayHtml(content);
    setCurrentDisplayType("html");
  };

  const handleDisplayProductId = async (productId: string, flightInfo?: FlightOption, flightList?: FlightOption[],
    callback?: () => void
  ) => {
    try {
      // 获取产品数据并检查语言
      messageApi.loading({
        content: t('copilot.loadingProduct'),
        key: "product-loading",
      });

      const result = await getProductById(productId, i18n.language);
      messageApi.destroy("product-loading");

      if (!result.data || !result.data.pageDiv) {
        messageApi.error(t('copilot.productNotFound'));
        return;
      }

      // 检查返回的语言是否与当前语言匹配
      if (result.data.language && result.data.language !== i18n.language) {
        callback?.();
        return
      }

      // 语言匹配，正常显示产品详情
      setDisplayProductId(productId);
      setFlightState && flightInfo && flightList && setFlightState({ flightInfo, flightList });
      setCurrentDisplayType("product");

    } catch (error) {
      console.error("获取产品数据失败:", error);
      messageApi.error(t('copilot.productLoadError'));
    }
  };

  // 处理总结功能
  const handleSummaryClick = async (
    content: string,
    type: "html" | "product",
    metadata: { answerId: string, messageItemId: string },
  ) => {
    try {
      let actualContent = content;

      if (type === "product") {
        // 对于产品ID，需要获取产品的pageDiv内容
        try {
          messageApi.loading({
            content: t('copilot.loadingProduct'),
            key: "product-loading",
          });
          const result = await getProductById(content, 'zh');
          if (result.data && result.data.pageDiv) {
            actualContent = result.data.pageDiv;
            messageApi.destroy("product-loading");

            // 检查返回的语言是否与当前语言匹配
            if (result.data.language && result.data.language !== i18n.language) {
              const callback = (messageItem: MessageItem) => {
                const summaries = messageItem.answers.filter(a => a.id === metadata.answerId)[0]?.summaries
                saveProductMultilang({
                  productId: content,
                  languageCode: i18n.language,
                  pageContentMarkdown: result.data?.pageDiv || '',
                  translatedContent: summaries[summaries.length - 1].display,
                })
                messageApi.success(t('copilot.saveMultilangSuccess'));
              }

              // 语言不匹配时自动进行总结
              onRequest({
                question: actualContent,
                type: "summary",
                metadata: { content: actualContent, type: type },
                answerId: metadata.answerId,
              }, metadata.messageItemId, callback);
              return;
            }
          } else {
            throw new Error(t('copilot.productNotFound'));
          }
        } catch (error) {
          console.error("获取产品数据失败:", error);
          messageApi.error({
            content: t('copilot.productLoadError'),
            key: "product-loading",
          });
          return;
        }
      }

      // 通过 onRequest 发送总结请求，这样会自动处理流式响应和加载状态
      onRequest({
        question: actualContent,
        type: "summary",
        metadata: { content: actualContent, type: type },
        answerId: metadata.answerId,
      }, metadata.messageItemId);
    } catch (error) {
      console.error("总结请求失败:", error);
      messageApi.error(t('copilot.summaryError'));
    }
  };

  // 获取或生成当前会话的 chatId
  const getCurrentChatId = (): string => {
    if (!chatIds[curSession]) {
      const newChatId = generateChatId();
      const updatedChatIds = { ...chatIds, [curSession]: newChatId };
      setChatIds(updatedChatIds);
      saveToLocalStorage(STORAGE_KEYS.CHAT_IDS, updatedChatIds);
      return newChatId;
    }
    return chatIds[curSession];
  };

  // 统一的 STOPPED 操作处理函数
  const handleHumanInputRequired = (
    nodeId: string,
    nodeLabel: string,
    humanInputMessage: HumanInputMessage,
    nodeData?: any,
  ) => {
    setHumanInputModal({
      visible: true,
      nodeId,
      nodeLabel,
      humanInputMessage,
      nodeData,
    });
    return;
  };

  // 处理总结结果点击
  const handleSummaryResultClick = (summaryContent: string) => {
    // 直接使用传入的总结内容（现在包含真实内容而不是占位符）
    setDisplayHtml(summaryContent);
    setCurrentDisplayType("html");
  };

  // 处理保存多语言内容
  const handleSaveMultilang = async (summaryContent: string, originalContent: string, productId?: string) => {
    try {
      const saveRequest: SaveProductMultilangRequest = {
        productId: productId || "default", // 直接使用传入的productId参数
        languageCode: i18n.language,
        pageContentMarkdown: originalContent, // 中文原文
        translatedContent: summaryContent, // 翻译后的总结内容
      };

      console.log("保存多语言总结内容:", saveRequest);
      const result = await saveProductMultilang(saveRequest);
      console.log("多语言总结内容保存成功:", result);

      messageApi?.success(t('copilot.saveMultilangSuccess'));
    } catch (error) {
      console.error("保存多语言总结内容失败:", error);
      messageApi?.error(t('copilot.saveMultilangError'));
    }
  };

  // 处理总结流更新 - 将非think内容发送到WorkArea
  const handleSummaryStreamUpdate = (content: string) => {
    setDisplayHtml(content);
    setCurrentDisplayType("html");
  };

  const { chat, onRequest, setChat, loading, abortChat } = useChatAgent(
    getCurrentChatId(),
    handleHumanInputRequired,
    handleSummaryStreamUpdate,
  );

  // 创建带有 flow_html、flow_product_id 和 flow_summary_result 支持的消息渲染器
  const messageRenderer = createMarkdownRenderer(
    handleDisplayHtml, // onFlowHtmlClick
    handleDisplayProductId, // onFlowProductIdClick
    handleSummaryClick, // onSummaryClick
    handleSummaryResultClick, // onSummaryResultClick
    handleSaveMultilang, // onSaveMultilang
  );

  // ==================== Event Handlers ====================

  // 处理人工确认决定
  const handleHumanInputDecision = async (
    decision: "proceed" | "reject" | "cancel",
    data: Record<string, any> = {},
    msgInfo?: string,
  ) => {
    try {
      const decisionDict = {
        proceed: t('copilot.adoptRoute'),
        reject: t('copilot.aiGenerateRoute'),
        cancel: t('copilot.cancelOperation'),
      };
      if (humanInputModal.humanInputMessage === null) {
        messageApi.error(t('copilot.noValidInput'));
        return;
      }

      humanInputModal.humanInputMessage.data.action = decision;

      // 通过 onRequest 发送请求，这样会自动处理流式响应
      let flightInfo
      let flightList
      let question
      if (data.flightInfo) {
        flightInfo = data.selectedFlight;
        flightList = data.flightList;
        question = data.flightInfo;
      }
      onRequest(
        {
          question: question || "",
          type: "humanInput",
          metadata: {
            action: decision, nodeId: humanInputModal.nodeId,
            flightInfo: flightInfo, flightList: flightList
          },
          answerId: humanInputModal.humanInputMessage.answerId,
        },
        humanInputModal.humanInputMessage.messageItemId,
      );

      setHumanInputModal({
        visible: false,
        nodeId: "",
        nodeLabel: "",
        nodeData: null,
        humanInputMessage: null,
      });

      messageApi.success(`${t('copilot.operationConfirmed')}：${msgInfo || decisionDict[decision]}`);
    } catch (error) {
      console.error("Failed to send human input decision:", error);
    }
  };

  const handleUserSubmit = (val?: string, messageItemId?: string) => {
    if (!val) {
      onRequest({
        question: "",
        type: "reask",
        metadata: {},
      },
        messageItemId
      );
    } else {
      onRequest({
        question: val,
        type: "question",
        metadata: {},
      });
    }
  };

  const onPasteFile = (_: File, files: FileList) => {
    for (const file of files) {
      attachmentsRef.current?.upload(file);
    }
    setAttachmentsOpen(true);
  };

  const handleNewSession = () => {
    if (loading) {
      messageApi.error(
        t('copilot.requestInProgress'),
      );
      return;
    }

    if (chat?.messageItems?.length) {
      const timeNow = dayjs().valueOf().toString();
      setTimeout(() => {
        const updatedSessionList = [
          { key: timeNow, label: t('copilot.newSession'), group: t('copilot.today') },
          ...sessionList,
        ];

        // 为新会话生成 chatId
        const newChatId = generateChatId();
        const updatedChatIds = { ...chatIds, [timeNow]: newChatId };

        setSessionList(updatedSessionList);
        setChatIds(updatedChatIds);
        setCurSession(timeNow);
        setChat(createChat(newChatId));

        // 保存到 localStorage
        saveToLocalStorage(STORAGE_KEYS.SESSION_LIST, updatedSessionList);
        saveToLocalStorage(STORAGE_KEYS.CHAT_IDS, updatedChatIds);
        saveToLocalStorage(STORAGE_KEYS.CURRENT_SESSION, timeNow);
      }, 100);
    } else {
      messageApi.error(t('copilot.alreadyNewSession'));
    }
  };

  const handleSessionChange = async (val: string) => {
    if (loading) {
      messageApi.warning(
        t('copilot.switchSessionInProgress'),
      );
      return;
    }
    setTimeout(() => {
      setCurSession(val);
      const sessionMessages = messageHistory?.[val] || [];
      setChat(sessionMessages);

      // 如果新会话没有 chatId，生成一个
      if (!chatIds[val]) {
        const newChatId = generateChatId();
        const updatedChatIds = { ...chatIds, [val]: newChatId };
        setChatIds(updatedChatIds);
        saveToLocalStorage(STORAGE_KEYS.CHAT_IDS, updatedChatIds);
      }

      // 保存当前会话
      saveToLocalStorage(STORAGE_KEYS.CURRENT_SESSION, val);
    }, 100);
  };

  const handleClearHistory = () => {
    // 清除 localStorage
    Object.values(STORAGE_KEYS).forEach((key) => {
      localStorage.removeItem(key);
    });

    // 重置状态
    setMessageHistory({});
    setSessionList([
      {
        key: "0",
        label: t('copilot.newSession'),
        group: t('copilot.history'),
      },
    ]);
    setChatIds({});
    setCurSession("0");

    // 为默认会话生成 chatId
    const defaultChatId = generateChatId();
    setChat(createChat(defaultChatId));
    const initialChatIds = { "0": defaultChatId };
    setChatIds(initialChatIds);
    saveToLocalStorage(STORAGE_KEYS.CHAT_IDS, initialChatIds);

    messageApi.success(t('copilot.chatHistoryCleared'));
  };

  // ==================== Effects ====================
  // 初始化加载当前会话的消息
  useEffect(() => {
    const savedMessages = messageHistory[curSession] || [];
    if (savedMessages.messageItems?.length > 0) {
      setChat(savedMessages);
    }
  }, [curSession]); // 只依赖 curSession，避免循环更新

  // 保存消息历史到 localStorage
  useEffect(() => {
    if (chat?.messageItems?.length) {
      setMessageHistory((prev) => {
        const newMessageHistory = {
          ...prev,
          [curSession]: chat,
        };
        saveToLocalStorage(STORAGE_KEYS.MESSAGE_HISTORY, newMessageHistory);
        return newMessageHistory;
      });
    }
  }, [chat, curSession]);

  // 保存会话列表到 localStorage
  useEffect(() => {
    saveToLocalStorage(STORAGE_KEYS.SESSION_LIST, sessionList);
  }, [sessionList]);

  // 保存当前会话到 localStorage
  useEffect(() => {
    saveToLocalStorage(STORAGE_KEYS.CURRENT_SESSION, curSession);
  }, [curSession]);

  // ==================== Render Components ====================
  const chatHeader = (
    <div className={styles.chatHeader}>
      <div className={styles.headerTitle}>✨ {t('chatbox.title')}</div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 1 }}>
        <LanguageSwitcher />
      </div>
      <Space size={0}>
        <Button
          type="text"
          icon={<PlusOutlined />}
          onClick={handleNewSession}
          className={styles.headerButton}
        />
        <Popover
          placement="bottom"
          styles={{ body: { padding: 0, maxHeight: 600 } }}
          content={
            <Conversations
              items={sessionList?.map((i) =>
                i.key === curSession
                  ? { ...i, label: `[${t('common.current')}] ${i.label}` }
                  : i,
              )}
              activeKey={curSession}
              groupable
              onActiveChange={handleSessionChange}
              styles={{ item: { padding: "0 8px" } }}
              className={styles.conversations}
            />
          }
        >
          <Button
            type="text"
            icon={<CommentOutlined />}
            className={styles.headerButton}
          />
        </Popover>
        <Popconfirm
          title={t('chatbox.operations.clearHistory')}
          description={t('chatbox.operations.clearHistoryConfirm', { count: sessionList.length })}
          onConfirm={handleClearHistory}
          okText={t('common.confirm')}
          cancelText={t('common.cancel')}
        >
          <Button
            type="text"
            icon={<DeleteOutlined />}
            className={styles.headerButton}
            title={t('chatbox.operations.clearHistoryTitle', { count: sessionList.length })}
          />
        </Popconfirm>
        <Button
          type="text"
          icon={<CloseOutlined />}
          onClick={() => setCopilotOpen(false)}
          className={styles.headerButton}
        />
      </Space>
    </div>
  );

  const chatList = (
    <div className={styles.chatList}>
      {chat?.messageItems?.length ? (
        <Bubble.List
          style={{ height: "100%", paddingInline: 16 }}
          items={chat.messageItems?.flatMap((i) => {
            const question = {
              content: i.question,
              role: "user",
              ...i,
            };
            if (i.answer_length === 0) {
              return [question];
            }
            const answer = i.answers[i.answer_length - 1];
            const answer_rendered = {
              content: answer,
              role: "assistant",
              ...answer,
              messageRender: messageRenderer,
              classNames: {
                content:
                  i.answers[i.answer_length - 1].status === "pending"
                    ? styles.loadingMessage
                    : "",
              },
              typing:
                i.answers[i.answer_length - 1].status === "pending"
                  ? { step: 5, interval: 20, suffix: <>💗</> }
                  : false,
            };
            return [question, answer_rendered];
          })}
          roles={{
            assistant: {
              placement: "start",
              footer: (content: Answer) => (
                <div style={{ display: "none" }}>
                  {/* Add action buttons here if needed */}
                  <Button
                    onClick={() => {
                      handleUserSubmit("", content.messageItemId)
                    }}
                    size="small"
                    color="default"
                    variant="text"
                    icon={<RedoOutlined />}
                  />
                </div>
              ),
              loadingRender: () => (
                <Space>
                  <Spin size="small" />
                  {t('chatbox.generating')}
                </Space>
              ),
            },
            user: { placement: "end" },
          }}
        />
      ) : (
        <Welcome
          variant="borderless"
          title={t('chatbox.welcomeTitle')}
          description={t('chatbox.welcomeDescription')}
          className={styles.chatWelcome}
        />
      )}
    </div>
  );

  const sendHeader = (
    <Sender.Header
      title={t('chatbox.upload.title')}
      styles={{ content: { padding: 0 } }}
      open={attachmentsOpen}
      onOpenChange={setAttachmentsOpen}
      forceRender
    >
      <Attachments
        ref={attachmentsRef}
        beforeUpload={() => false}
        items={files}
        onChange={({ fileList }) => setFiles(fileList)}
        placeholder={(type) =>
          type === "drop"
            ? { title: t('chatbox.upload.dropHere') }
            : {
              icon: <CloudUploadOutlined />,
              title: t('chatbox.upload.title'),
              description: t('chatbox.upload.description'),
            }
        }
      />
    </Sender.Header>
  );

  const chatSender = (
    <div className={styles.chatSend}>
      <div className={styles.sendAction}></div>
      <Suggestion
        items={getMockSuggestions(t)}
        onSelect={(itemVal) => setInputValue(`[${itemVal}]:`)}
      >
        {({ onTrigger, onKeyDown }) => (
          <Sender
            loading={loading}
            value={inputValue}
            onChange={(v) => {
              // onTrigger(v === "/");
              setInputValue(v);
            }}
            onSubmit={() => {
              handleUserSubmit(inputValue);
              setInputValue("");
            }}
            onCancel={() => {
              abortChat();
            }}
            allowSpeech
            placeholder={
              loading
                ? t('chatbox.generating')
                : t('chatbox.placeholder')
            }
            onKeyDown={onKeyDown}
            header={sendHeader}
            // prefix={
            //   <Button
            //     type="text"
            //     icon={<PaperClipOutlined style={{ fontSize: 18 }} />}
            //     onClick={() => setAttachmentsOpen(!attachmentsOpen)}
            //   />
            // }
            onPasteFile={onPasteFile}
            actions={(_, info) => {
              const { SendButton, LoadingButton } = info.components;
              return (
                <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
                  {loading ? (
                    <LoadingButton type="default" />
                  ) : (
                    <SendButton type="primary" />
                  )}
                </div>
              );
            }}
          />
        )}
      </Suggestion>
    </div>
  );

  return (
    <>
      <div
        className={styles.copilotChat}
        style={{ width: copilotOpen ? 400 : 0 }}
      >
        {chatHeader}
        {chatList}
        {chatSender}
      </div>

      {/* 人工确认弹窗 */}
      <HumanInputModal
        humanInputModal={humanInputModal}
        loading={loading}
        onDecision={handleHumanInputDecision}
      />
    </>
  );
};

export default Copilot;
